package global

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"sync"
	"time"
)

var DB *gorm.DB

func initGorm(wg *sync.WaitGroup) {
	defer wg.Done()
	var err error

	// 数据库配置信息
	dsn := CONFIG.Mysql.Username + ":" + CONFIG.Mysql.Password + "@tcp(" + CONFIG.Mysql.Path + ":" + CONFIG.Mysql.Port + ")/" + CONFIG.Mysql.DbName + "?" + CONFIG.Mysql.Config

	if DEV {
		newLogger := logger.New(
			log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
			logger.Config{
				SlowThreshold:             time.Second, // 慢 SQL 阈值
				LogLevel:                  logger.Info, // 日志级别
				IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
				Colorful:                  true,        // 禁用彩色打印
			},
		)
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			Logger: newLogger,
		})
	} else {
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	}

	if err != nil {
		panic(err)
	}
}
